package com.cloudkinto.service.shipprice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.utils.dict.StaticDict;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.company.CompanyOperatePriceService;
import com.cloudkinto.service.dic.DicBusinessItemService;
import com.cloudkinto.service.dic.vo.DicItemRes;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.region.JpRegionService;
import com.cloudkinto.service.shipprice.DimensService;
import com.cloudkinto.service.shipprice.ShipPriceService;
import com.cloudkinto.service.shipprice.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author ding
 * @since 2020-06-09
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class ShipPriceServiceImpl extends ServiceImpl<ShipPriceDao, ShipPriceDo> implements ShipPriceService {
    @Autowired
    private ShipPriceDao dao;
    @Autowired
    private StorageDao mStorageDao;
    @Autowired
    private DimensService mDimensService;
    @Autowired
    private JpRegionDao jpRegionDao;
    @Autowired
    private JpStateDao jpStateDao;
    @Autowired
    private DimensDao dimensDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private DicBusinessItemService dicBusinessItemService;
    @Autowired
    private ProductInfoDao mProductDao;
    @Autowired
    private JpRegionService mRegionService;
    @Autowired
    private FbaStorageDao fbaStorageDao;
    @Autowired
    private OrderOutputService orderOutputService;
    @Autowired
    private CompanyOperatePriceService companyOperatePriceService;



    @Override
    public List<ShipPriceDo> queryByRegionAndSize(String postCode, double[] packageSize, Integer cod, Integer shipmentType, Long storageId, int version, Long companyId) {
        return queryByRegionAndSize(mRegionService.getStateIdByPostCode(postCode), packageSize, cod, shipmentType, storageId, version, null, companyId);
    }

    @Override
    public List<ShipPriceDo> queryByRegionAndSize(String postCode, double[] packageSize, Integer cod, Integer shipmentType, Long storageId, int version, Integer bundling, Long companyId) {
        return queryByRegionAndSize(mRegionService.getStateIdByPostCode(postCode), packageSize, cod, shipmentType, storageId, version, bundling, companyId);

    }



    /**
     * 根据 三边和/重量/  算运费
     *
     * @param stateId   所属地区
     * @param storageId 仓库id
     * @param version   费用版本
     * @param cod        0 代表 不是货到付款
     * @param shipmentType 0代表 不是次日达
     * @return
     */
    @Override
    public List<ShipPriceDo> queryByRegionAndSize(Long stateId, double[] size, Integer cod, Integer shipmentType, Long storageId, int version, Integer bundling, Long companyId) {
        double[] packageSize = this.initSize(size);
        List<ShipPriceDo> shipPriceList = new ArrayList<>();
        List<DimensDo> dimensIds = mDimensService.listBySizeAndWeight(packageSize[3], packageSize[0], packageSize[1], packageSize[2], cod, shipmentType, storageId, bundling, companyId);
        if (dimensIds.size() < 1) {
            return shipPriceList;
        }
        double materialPrice = 0;
        if (packageSize[4] != 0D && packageSize[4] != -1) {
            materialPrice =  companyOperatePriceService.getPackFee((long)packageSize[4], packageSize[0]+packageSize[1]+packageSize[2], companyId);
        }
        ShipPriceDo less = null;
        for (DimensDo dimensDo : dimensIds) {
            if (DicBusinessItemConstant.yamatoExpressBox.equals(dimensDo.getTrackId())) {
                continue;
            }
            ShipPriceDo priceDo = this.getShipPrice(dimensDo, stateId, version, materialPrice, less);
            if (priceDo == null) {
                continue;
            }
            less = priceDo;
        }
        //再去算黑猫盒子的
        dimensIds = mDimensService.listBySizeAndWeight(packageSize[3], packageSize[5], packageSize[6], packageSize[7], cod, shipmentType, storageId, DicBusinessItemConstant.yamatoExpressBox, bundling, companyId);
        for (DimensDo dimensDo : dimensIds) {
            ShipPriceDo priceDo = this.getShipPrice(dimensDo, stateId, version, materialPrice, less);
            if (priceDo == null) {
                continue;
            }
            less = priceDo;
        }
        if (less != null) {
            shipPriceList.add(less);
        }
        return shipPriceList;
    }


    public ShipPriceDo getShipPrice(DimensDo dimensDo, Long stateId, int version, double materialPrice, ShipPriceDo less) {
        LambdaQueryWrapper<ShipPriceDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShipPriceDo::getStateId, stateId)
                .eq(ShipPriceDo::getDimensId, dimensDo.getId())
                .eq(ShipPriceDo::getActive, 1)
                .eq(ShipPriceDo::getVersion, version)//特殊报价
                .last("order by id desc limit 1");
        ShipPriceDo ship = baseMapper.selectOne(wrapper);
        if (ship == null) {
            wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShipPriceDo::getStateId, stateId)
                    .eq(ShipPriceDo::getDimensId, dimensDo.getId())
                    .eq(ShipPriceDo::getActive, 1)
                    .eq(ShipPriceDo::getVersion, 2) // 普通报价
                    .last("order by id desc limit 1");
            ship = baseMapper.selectOne(wrapper);
        }
        if (ship == null) {
            return null;
        }
        //比价格之前 需要加上 耗材费 如果是黑猫盒子 就不需要耗材费
        if (!DicBusinessItemConstant.yamatoExpressBox.equals(dimensDo.getTrackId())) {
            ship.setPrice(ship.getPrice() + materialPrice);
        }
        if (less == null || ship.getPrice() < less.getPrice()) {
            less = ship;
            //算成本
            wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShipPriceDo::getStateId, stateId)
                    .eq(ShipPriceDo::getDimensId, dimensDo.getId())
                    .eq(ShipPriceDo::getActive, 1)
                    .eq(ShipPriceDo::getVersion, 1) // 成本报价
                    .last("order by id desc limit 1");
            ShipPriceDo originalShip = baseMapper.selectOne(wrapper);
            if (originalShip != null) {
                less.setOriginalPrice(originalShip.getOriginalPrice());
            }
        }
        return less;
    }

    @Override
    public ShipPriceDo queryByRegionAndSize(Long stateId, double[] packageSize, Long storageId, Long trackId, int version, Long companyId) {
        return queryByRegionAndSize(stateId, packageSize, 0, 0, storageId, trackId, version, null, companyId);
    }


    public ShipPriceDo queryByRegionAndSize(String postCode, double[] packageSize, Integer cod, Integer shipmentType, Long storageId, Long trackId, int version, Integer bundling, Long companyId) {
        return queryByRegionAndSize(mRegionService.getStateIdByPostCode(postCode), packageSize, cod, shipmentType, storageId, trackId, version, bundling, companyId);
    }


    /**
         * 根据 三边和/重量/  算运费
         *
         * @param stateId   所属地区
         * @param storageId 仓库id
         * @param version   费用版本
         * @return
         */
    @Override
    public ShipPriceDo queryByRegionAndSize(Long stateId, double[] size, Integer cod, Integer shipmentType, Long storageId, Long trackId, int version, Integer bundling, Long companyId) {
        double[] packageSize = this.initSize(size);
        ShipPriceDo res = null;
        List<DimensDo> dimensDos;
        if (DicBusinessItemConstant.yamatoExpressBox.equals(trackId)) {
             dimensDos = mDimensService.listBySizeAndWeight(packageSize[3], packageSize[5], packageSize[6], packageSize[7], cod, shipmentType, storageId, trackId, bundling, companyId);
        }
        else {
             dimensDos = mDimensService.listBySizeAndWeight(packageSize[3], packageSize[0], packageSize[1], packageSize[2], cod, shipmentType, storageId, trackId, bundling, companyId);
        }
        if (dimensDos.size() < 1) {
            return null;
        }
        List<Object> dimensIds = dimensDos.stream().map(DimensDo::getId).collect(Collectors.toList());
        LambdaQueryWrapper<ShipPriceDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShipPriceDo::getStateId, stateId)
                .in(ShipPriceDo::getDimensId, dimensIds)
                .eq(ShipPriceDo::getActive, 1)
                .eq(ShipPriceDo::getVersion, version);
        List<ShipPriceDo> shipPrices = baseMapper.selectList(wrapper);
        if (shipPrices != null && shipPrices.size() > 0) {
            res = shipPrices.get(0);
            for (ShipPriceDo ship : shipPrices) {
                if (ship.getPrice() < res.getPrice()) {
                    res = ship;
                }
            }
        } else {
            wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShipPriceDo::getStateId, stateId)
                    .in(ShipPriceDo::getDimensId, dimensIds)
                    .eq(ShipPriceDo::getActive, 1)
                    .eq(ShipPriceDo::getVersion, 2);
            shipPrices = baseMapper.selectList(wrapper);
            if (shipPrices != null && shipPrices.size() > 0) {
                res = shipPrices.get(0);
                for (ShipPriceDo ship : shipPrices) {
                    if (ship.getPrice() < res.getPrice()) {
                        res = ship;
                    }
                }
            }
        }
        return res;
    }

    public double[] initSize(double[] size) {
        double[] packageSize = new double[8];
        if (size.length < 8 || (size[5] == 0 && size[6] == 0 && size[7] == 0)) {
            packageSize[0] = size[0];
            packageSize[1] = size[1];
            packageSize[2] = size[2];
            packageSize[3] = size[3];
            packageSize[4] = 0;
            packageSize[5] = size[0];
            packageSize[6] = size[1];
            packageSize[7] = size[2];
        }
        else {
            packageSize = size;
        }
        return packageSize;
    }

    @Override
    public SingleResult warehousingPrice(WarehousingPriceReq req, Long userId, Long companyId) {
        StorageDo storageDo = storageDao.selectById(req.getStorageId());
        if (storageDo == null) {
            throw new BizExceptionI18(SysConstant.Storage_IsNull);
        }
        double price;
        //梯度计算仓储费
        if (req.getDays() <= 60) {
            price = storageDo.getDayPrice() * req.getDays();
        } else if (req.getDays() > 60 && req.getDays() <= 120) {
            price = storageDo.getDayPrice() * 60 + (req.getDays() - 60) * storageDo.getDayPrice1();
        } else {
            price = storageDo.getDayPrice() * 60 + (req.getDays() - 60) * storageDo.getDayPrice1() + (req.getDays() - 120) * storageDo.getDayPrice2();
        }
        double volume = req.getLength() * req.getWidth() * req.getHeight() / 1000000;
        double result = volume * price;
        return SingleResult.success(result);
    }

    @Override
    public SingleResult computePrice(ComputePriceReq req, Long userId, Long companyId) {
        ShipPriceRes res = new ShipPriceRes();

        CompanyDo companyDo = companyDao.selectById(companyId);

        StorageDo storageDo = storageDao.selectById(req.getStorageId());

        JpRegionDo jpRegionDo = jpRegionDao.selectById(req.getRegionId());
        double[] size = this.getSizeOrderDesc(req.getLength(), req.getWidth(), req.getHeight());

        double[] packageSize = new double[8];
        packageSize[0] = size[0];
        packageSize[1] = size[1];
        packageSize[2] = size[2];
        packageSize[3] = req.getWeight();
        packageSize[4] = 0;
        packageSize[5] = size[0];
        packageSize[6] = size[1];
        packageSize[7] = size[2];

        List<ShipPriceDo> shipPriceDos = this.queryByRegionAndSize(jpRegionDo.getJpStateId(), packageSize, 0, 0,storageDo.getId(), companyDo.getShipPriceVersion(), 0, companyId);

        if (!CollectionUtils.isEmpty(shipPriceDos)) {
            res.setPrice(shipPriceDos.get(0).getPrice());
            res.setStorage(storageDo.getStorageName());
            DimensDo dimensDo = dimensDao.selectById(shipPriceDos.get(0).getDimensId());
            DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(dimensDo.getTrackId());
            res.setTrackName(businessItemDo.getDicItemValue());
        }


        return SingleResult.success(res);
    }

    @Override
    public SingleResult computeInit() {
        Map result = new HashMap();

        List<Map> storageList = new ArrayList<>();
        List<StorageDo> storageDoList = storageDao.selectList(new LambdaQueryWrapper<StorageDo>().eq(StorageDo::getCountryType,1));
        if (!CollectionUtils.isEmpty(storageDoList)) {
            storageDoList.forEach(storageDo -> {
                Map map = new HashMap();
                map.put("id", storageDo.getId());
                map.put("value", storageDo.getStorageName());
                storageList.add(map);
            });
        }
        result.put("storageList", storageList);

        List<Map> fbaStorageList = new ArrayList<>();
        List<FbaStorageDo> fbaStorageDoList = fbaStorageDao.selectList(null);
        if (!CollectionUtils.isEmpty(fbaStorageDoList)) {
            fbaStorageDoList.forEach(storageDo -> {
                Map map = new HashMap();
                map.put("id", storageDo.getId());
                map.put("value", storageDo.getFbaName());
                map.put("codeValue", storageDo.getFbaCode());
                fbaStorageList.add(map);
            });
        }
        result.put("fbaStorageList", fbaStorageList);

        List<Map> regionList = new ArrayList<>();
        List<JpRegionDo> regionDoList = jpRegionDao.selectList(null);
        if (!CollectionUtils.isEmpty(regionDoList)) {
            regionDoList.forEach(regionDo -> {
                Map map = new HashMap();
                map.put("id", regionDo.getId());
                map.put("value", regionDo.getName());
                regionList.add(map);
            });
        }
        result.put("regionList", regionList);

        return SingleResult.success(result);
    }


    /**
     * 计算多个不同sku
     *
     * @param packageDetail
     * @return float[]{最长边.次长边,短边和，重量}
     */
    @Override
    public double[] getMulitSkuSize(List<OrderOutputProductDo> packageDetail) {
        List<ProductMsgReq> list = new ArrayList<>();
        for (OrderOutputProductDo pro : packageDetail) {
            ProductMsgReq req = new ProductMsgReq();
            BeanUtils.copyProperties(pro, req);
            list.add(req);
        }
        return this.getMulitSkuSizeReq(list);
    }


    public double[] getMulitSkuSizeReq(List<ProductMsgReq> packageDetail) {
        double[] finalSize = new double[4];
        if (packageDetail != null && packageDetail.size() > 0) {
            for (ProductMsgReq productDetail :
                    packageDetail) {
                finalSize = countSameSkuSize(finalSize, productDetail.getProductId(), productDetail.getCount());
            }
        }
        return finalSize;
    }

    /**
     * 获取多个SKu的操作费
     *
     * @param packageDetail
     * @param companyId
     * @return
     */
    @Override
    public int getMulitSkuOperationFee(List<OrderOutputProductDo> packageDetail, String companyId) {
        int fee = 0;
        if (packageDetail != null && packageDetail.size() > 0) {
            for (OrderOutputProductDo productDetail :
                    packageDetail) {
                fee += getSameSkuOperationFee(productDetail.getProductId(), productDetail.getCount(), companyId);
            }
        }
        return fee;
    }

    /**
     * 获取多个相同SKu的操作费
     *
     * @param productId
     * @param count
     * @param companyId
     * @return
     */
    @Override
    public int getSameSkuOperationFee(Long productId, int count, String companyId) {
        int fee = 0;
        ProductInfoDo productInfoDo = mProductDao.selectById(productId);
        float totalSize = productInfoDo.getWidth() + productInfoDo.getHeight() + productInfoDo.getLength();
        if (companyId.equals("C1030")) {
            fee = fee + 80 + (count - 1) * 50;
        } else if (totalSize < 60) {
            fee = fee + 100 + (count - 1) * 50;
        } else {
            fee = fee + 200 + (count - 1) * 100;
        }
        return fee;
    }


    /**
     * 计算单个/多个相同sku
     *
     * @param finalSize
     * @param productId
     * @param count
     * @return
     */
    @Override
    public double[] countSameSkuSize(double[] finalSize, Long productId, int count) {
        ProductInfoDo productInfoDo = mProductDao.selectById(productId);
      return countSameSkuSizeNew(finalSize, productInfoDo, count);
    }

    /**
     * 计算单个/多个相同sku
     *
     * @param count
     * @return
     */
    @Override
    public double[] countSameSkuSizeNew(double[] inputSize, ProductInfoDo productBean, int count) {
        if (productBean == null) return new double[4];
        return countSameSkuSizeNew(inputSize,Double.valueOf(String.valueOf( productBean.getWidth()))
                ,Double.valueOf(String.valueOf( productBean.getHeight())), Double.valueOf(String.valueOf(productBean.getLength())), Double.valueOf(String.valueOf(productBean.getWeight())), count);
    }

    /**
     * 计算单个/多个相同sku
     */
    @Override
    public double[] countSameSkuSizeNew(double[] inputSize, double size0, double size1, double size2, double weight, int count) {
        double[] smallSize = new double[]{32.2, 22.1, 3.1};
        double[] outSizeSize = new double[4];
        double[] size = getSizeOrderDesc(size0, size1, size2);
        if (Math.max(size[2], inputSize[2]) < smallSize[2] && inputSize[1] + size[1] * count < smallSize[1]
                && Math.max(size[0], inputSize[0]) < smallSize[0] &&
                (size[0] + size[1] + size[2]) < 60 && (inputSize[3] + weight * count) < 1 &&
                (Math.max(inputSize[0], size[0])) + inputSize[1] + size[1] * count + (Math.max(inputSize[2], size[2])) < 60  ) {
            //黑猫小包
            //最长边小于 31.2 次长边小于22.8 最短边小于2.5  三遍和小于 60 重量小于1kg  20.5 14.5
            outSizeSize[0] = inputSize[0];
            outSizeSize[2] = inputSize[2];
            outSizeSize[1] = inputSize[1] + size[1] * count;
        // }
        //最短边相加
        //如果最短边小于3，次短边相加小于34，次短边相加总边长小于55 ，则次短边相加
        // else if (((Math.max(inputSize[0], size[0])) + inputSize[1] + size[1] * count + (Math.max(inputSize[2], size[2])) < 60
        //         && inputSize[2] <= 3 && inputSize[0] <= smallSize[0] && inputSize[1] + size[1] * count <=  smallSize[0]) &&
        //         size[0] + size[1] + size[2] <  60 && size[2] <= smallSize[2] && size[0] <= smallSize[0]) {
        //     outSizeSize[0] = inputSize[0];
        //     outSizeSize[2] = inputSize[2];
        //     outSizeSize[1] = inputSize[1] + size[1] * count;
        } else {
            outSizeSize[0] = inputSize[0];
            outSizeSize[1] = inputSize[1];
            outSizeSize[2] = inputSize[2] + size[2] * count;
        }
        for (int i = 0; i < size.length; i++) {
            if (outSizeSize[i] < size[i]) {
                outSizeSize[i] = size[i];
            }
        }

        outSizeSize[3] = inputSize[3] + weight * count;
        double[] sizeTemp = this.getSizeOrderDesc(outSizeSize[0], outSizeSize[1], outSizeSize[2]);
        outSizeSize[0] = sizeTemp[0];
        outSizeSize[1] = sizeTemp[1];
        outSizeSize[2] = sizeTemp[2];
        return outSizeSize;
    }

    /**
     * 获取三边有大到小排序
     * * @param width
     *
     * @param height
     * @param length
     * @return
     */
    @Override
    public double[] getSizeOrderDesc(double width, double height, double length) {
        double[] floats = new double[]{width, height, length};
        for (int i = 0; i < floats.length; i++) {
            for (int j = 0; j < floats.length - i - 1; j++) {   // 这里说明为什么需要-1
                if (floats[j] < floats[j + 1]) {
                    double temp = floats[j];
                    floats[j] = floats[j + 1];
                    floats[j + 1] = temp;
                }
            }
        }
        return floats;
    }


    /**
     * 获取物流方式 并且获取差价
     */
    @Override
    public List<Map<String, Object>> getTrackList(TrackReq req, Long companyId) {
        if (req.getList() == null || req.getList().size() == 0) {
            return null;
        }
//        double[] size = this.getMulitSkuSizeReq(req.getList());

        List<OrderOutputProductDo> productDoList = new ArrayList<>();
        for (ProductMsgReq productMsgReq : req.getList()) {
            OrderOutputProductDo productDo = new OrderOutputProductDo();
            productDo.setProductId(productMsgReq.getProductId());
            productDo.setCount(productMsgReq.getCount());
            productDoList.add(productDo);
        }
        List<Map<String, Object>> trackList = this.getTrackList(productDoList, req.getStorageId(), req.getPostCode(), req.getShipmentType(), req.getCod(), companyId);
        return trackList;
    }



    @Override
    public List<Map<String, Object>> getTrackList(List<OrderOutputProductDo> productDoList, Long storageId, String postCode, Integer shipmentType, int cod, Long companyId) {
        if (productDoList == null || productDoList.isEmpty()) {
            return null;
        }

        List<Long> productIds = productDoList.stream().map(OrderOutputProductDo::getProductId).distinct().collect(Collectors.toList());
        Map<Long, ProductInfoDo> productmMap = new HashMap<>();
        if (!productIds.isEmpty()) {
            List<ProductInfoDo> productBeans = mProductDao.selectList(new LambdaQueryWrapper<ProductInfoDo>()
                    .in(ProductInfoDo::getId, productIds));
            productmMap = productBeans.stream().collect(Collectors.toMap(ProductInfoDo::getId, i -> i, (v1, v2) -> v1));
        }
//        int sizeType = orderOutputService.jugSizeType(size, req.getStorageId(), productDoList);
        StorageDo storageDo = storageDao.selectById(storageId);
        double[] packageSize = orderOutputService.getMaxPackageSize(storageId, productDoList, true, null, companyId, productmMap, storageDo);
        double materialPrice = 0;
        double materialId = packageSize[4];
        if ( materialId != 0D && materialId != -1) {
            materialPrice =  companyOperatePriceService.getPackFee((long)materialId, packageSize[0]+packageSize[1]+packageSize[2], companyId);
        }
        List<DicItemRes> dicItemList = dicBusinessItemService.getDicItemList(DicBusinessConstant.trackCompany);
        Map<Long, List<DicItemRes>> parentCollect = dicItemList.stream().collect(Collectors.groupingBy(DicItemRes::getParentId));
        List<Map<String, Object>> resList = new ArrayList<>();

        Double price = null;
        for (Long parentId : parentCollect.keySet()) {
            Map<String, Object> map = new HashMap<>();
            List<DicItemRes> trackList = parentCollect.get(parentId);
            Double cheapPrice = null;
            if (DicBusinessItemConstant.yamatoExpressA.equals(parentId)) {
                continue;
            }
            DicItemRes item = null;
            for (DicItemRes dicItemRes : trackList) {

//                if (req.getCod() > 0 && !DicBusinessItemConstant.sagawaExpress.equals(dicItemRes.getId())) {
//                    //货到付款 只支持佐川
//                    continue;
//                }
                ShipPriceDo priceDo = this.queryByRegionAndSize(postCode, packageSize, cod, shipmentType, storageId, dicItemRes.getId(), 1, 0, companyId);
                if (priceDo == null) {
                    continue;
                }
                //比价格之前 需要加上 耗材费 如果是黑猫盒子 就不需要耗材费
                double shipPrice = priceDo.getPrice();
                if (!DicBusinessItemConstant.yamatoExpressBox.equals(dicItemRes.getId())) {
                    shipPrice += materialPrice;
                }
                if (cheapPrice == null || cheapPrice > shipPrice) {
                    cheapPrice = shipPrice;
                    item = dicItemRes;
                }
            }
            if (cheapPrice == null) {
                continue;
            }
            if (!(DicBusinessItemConstant.xinongExpress.equals(item.getId()) || DicBusinessItemConstant.yamatoExpressJCB.equals(item.getId())) && (price == null || price > cheapPrice)) {
                price = cheapPrice;;
            }
            map.put("id", item.getId());
            map.put("parentId", item.getParentId());
            map.put("value", StaticDict.Track_Type.getText(item.getParentId()));
            map.put("price", cheapPrice);
            map.put("pageSize", packageSize);
            resList.add(map);
        }
        if (price == null) {
            price = 0d;
        }
        for (Map<String, Object> map : resList) {//1500 1.6  3000 1.4  6000 1.2
            double diffPrice = (Double.parseDouble(map.get("price").toString()) - price);
            if (diffPrice <= 1500) {
                diffPrice = diffPrice * 1.6;
            }
            else if (diffPrice <= 3000) {
                diffPrice = diffPrice * 1.4;
            }
            else {
                diffPrice = diffPrice * 1.2;
            }
            if (DicBusinessItemConstant.xinongExpress.equals(map.get("id")) || DicBusinessItemConstant.yamatoExpressJCB.equals(map.get("id"))) {
                //西农设置无差价
                diffPrice = 0;
            }
            map.put("diffPrice", diffPrice);
            if (diffPrice > 0) {
                map.put("value", map.get("value") + "(补差价:"+diffPrice+")");
            }
        }

        resList.sort(new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Object price1 = o1.get("price");
                Object price2 = o2.get("price");
                double v1 = Double.parseDouble(price1.toString());
                double v2 = Double.parseDouble(price2.toString());
                return Double.compare(v1, v2);
            }
        });
        for (Map<String, Object> map : resList) {
            map.put("price", 0);
        }
        return resList;
    }

}
